<template>
  <a-drawer
    v-model:visible="visible"
    class="custom-class"
    title="全局配置-背景音乐"
    placement="right"
    width="800"
    :maskClosable="false"
  >
    <a-tabs v-model:activeKey="activeTab" @change="changeTab" type="card">
      <a-tab-pane :key="1" tab="智能匹配">
        <div style="display: flex">
          <div
            class="smart-MatchLf"
            :class="{ isChecked: isChecked }"
            @click="toggleCheckbox"
          >
            <h4 class="smart-Match-title">系统音乐随机</h4>
            <p class="smart-Match-desc">生成视频会从系统音乐库里自动匹配</p>
            <div class="checkbox" v-show="isChecked">
              <a-checkbox v-model:checked="isChecked"></a-checkbox>
            </div>
          </div>
        </div>
        <a-row type="flex" style="align-items: center; margin-top: 20px">
          <a-col style="font-weight: 600; margin-right: 10px"> 音量调节 </a-col>
          <a-col :span="11">
            <a-slider
              @change="changeVideoVolum"
              id="test"
              v-model:value="volume"
              :disabled="disabled"
              :max="100"
              :min="0"
            />
          </a-col>
          <a-col :span="2">{{ volume }}%</a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane :key="2">
        <template #tab>
          <span>
            <!-- <a-tooltip placement="bottom">
              <template #title
                ></template
              > -->
            自定义

            <!-- <QuestionCircleOutlined v-if="activeTab == 2" /> -->
            <!-- </a-tooltip> -->
          </span>
        </template>
        <p style="color: rgb(115, 122, 135)">
          选择多个音乐时，算法将为镜头组视频智能推荐不同的背景音乐
        </p>
        <div class="custom-list">
          <div class="custom-item1">
            <div class="custom-item1-add">
              <span>+</span>
            </div>
            <div class="custom-item1-option">
              <span class="hover-effect" @click="MusicLibraryHandle"
                ><upload-outlined />音乐库导入</span
              >
              <a-divider type="vertical" />
              <span class="hover-effect" @click="materialLibraryHandle"
                ><upload-outlined />素材库导入</span
              >
            </div>
          </div>
          <div
            class="custom-item"
            v-for="(item, index) in musicListArr"
            :key="index"
          >
            <div class="custom-item-lf" style="margin-right: 10px">
              <!-- <img
                src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
                alt=""
                style="width: 70px; height: 70px; border-radius: 4px"
              /> -->
              <span
                style="
                  display: inline-block;
                  width: 70px;
                  height: 70px;
                  border-radius: 4px;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
              >
                <cu-icon
                  type="icon-quanjuzimupeiyin"
                  style="font-size: 70px; color: rgb(122, 110, 186)"
                ></cu-icon>
              </span>
            </div>
            <div class="custom-item-rg">
              <div class="custom-item-rg-desc">
                <a-tooltip>
                  <template #title>{{ item?.material_name }}</template>
                  <span style="color: #484b4e" class="material_name">{{
                    item?.material_name
                  }}</span>
                </a-tooltip>

                <span style="color: #898b8d">{{
                  item?.material_duration_text
                }}</span>
              </div>
              <a-row type="flex" style="align-items: center; margin-top: 10px">
                <audio
                  :id="`audio${item.id}`"
                  controls
                  style="height: 30px; width: 100%"
                  :src="item.material_url"
                  @play="playAudio(item.id)"
                  @pause="pauseAudio(item.id)"
                  @ended="endPlayAudio(item.id)"
                ></audio>
              </a-row>
            </div>
            <div class="close" @click="delectHandle(item)">
              <close-outlined />
            </div>
          </div>
        </div>
        <a-row type="flex" style="align-items: center; margin-top: 20px">
          <a-col style="font-weight: 600; margin-right: 10px"> 音量调节 </a-col>
          <a-col :span="11">
            <a-slider
              id="test"
              v-model:value="volume"
              @change="changeVideoVolum"
              :min="0"
              :max="100"
            />
          </a-col>
          <a-col :span="2">{{ volume }}%</a-col>
        </a-row>
      </a-tab-pane>
      <template #rightExtra>
        <a-button
          type="link"
          v-if="activeTab == 2 && musicListArr?.length > 0"
          @click="emptyMusic"
          >清空</a-button
        >
      </template>
    </a-tabs>
    <template #footer>
      <a-row type="flex" justify="end">
        <a-button style="margin-right: 8px" type="primary" @click="summitHandle"
          >确认添加</a-button
        >
        <a-button @click="onClose">取消</a-button>
      </a-row>
    </template>
  </a-drawer>
  <materialLibrary ref="materiallibrary" />
  <MusicLibrary
    ref="musicLibrary"
    @updataMusic="updataMusic"
    :selectList="selectList"
  />
  <!-- 老素材库导入弹窗 -->
  <ChooseMaterial
    :isClip="false"
    material_type="audio"
    :multiple="true"
    :visible="materiallibraryShow"
    @close="closeChooseMaterial"
  />


  <!-- <newChooseMaterial
    :isClip="false"
    :visible="materiallibraryShow"
    modelType = "audio"
    @close="closeChooseMaterial($event, 'material_type')"
    /> -->
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  onMounted,
  ref,
  watch,
} from "vue";
import {
  QuestionCircleOutlined,
  UploadOutlined,
  CloudUploadOutlined,
  CaretRightOutlined,
  CloseOutlined,
  PauseOutlined,
} from "@ant-design/icons-vue";
import materialLibrary from "./materialLibrary.vue";
import MusicLibrary from "./MusicLibrary.vue";
import { useStore } from "vuex";
// 素材库
import newChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/newChooseMaterial.vue";

import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import _ from "lodash";
import { message } from "ant-design-vue";
import { set } from "@vueuse/core";
import {BGM_CONFIG_VOLUM} from '@/common/constants/shotstack'
export default defineComponent({
  components: {
    newChooseMaterial,
    QuestionCircleOutlined,
    UploadOutlined,
    CloudUploadOutlined,
    CaretRightOutlined,
    CloseOutlined,
    materialLibrary,
    MusicLibrary,
    PauseOutlined,
    ChooseMaterial, //素材库弹窗组件
  },
  setup() {
    const state = reactive({
      visible: false,
      activeTab: null, //控制tab栏切换
      materiallibrary: null, //新素材库组件实例（暂时用老系统）
      musicLibrary: null, //音乐库组件实例
      materiallibraryShow: false, //控制老系统素材库弹窗显示隐藏
      isChecked: true, //是否选中
    });

    // 仓库
    const store = useStore();
    /**
     * @param {bgm_config} 全局背景设置数据
     * @param {volume} 音量
     * @param {musicListArr} 音乐列表
     */
    let bgm_config = ref({});
    let volume = ref(BGM_CONFIG_VOLUM);
    let musicListArr = ref([]);

    const selectList = computed({
      get() {
        return musicListArr.value?.map((ele) => ele.id);
      },
    });

    // 打开弹窗
    const showDrawer = () => {
      // 复制全局文本背景音乐设置
      bgm_config.value = JSON.parse(
        JSON.stringify(store.state.shotstack.VideoMashup?.bgm_config)
      );
      musicListArr.value = bgm_config.value?.bgm_list || [];
      if (bgm_config.value.type == 0) {
        state.activeTab = 1;
      } else {
        state.activeTab = bgm_config.value.type;
      }
      console.log(state.activeTab);
      volume.value = bgm_config.value.volume * 100;
      state.visible = true;
    };

    // 关闭弹窗
    const onClose = () => {
      state.visible = false;
      if (currentAudio.value) {
        currentAudio.value.pause();
        currentAudio.value.currentTime = 0;
      }
    };

    // 素材库导入
    const materialLibraryHandle = () => {
      state.materiallibraryShow = true;
    };
    // 关闭老系统素材库导入弹窗, 获取音频文件列表
    const closeChooseMaterial = (data) => {
      if (data == undefined || (Array.isArray(data) && data.length == 0)) {
        state.materiallibraryShow = false; //关闭弹窗
        return;
      }
      data.forEach((item) => {
        const existingItem = musicListArr.value.find(
          (music) => music.id === item.id
        );
        if (!existingItem) {
          musicListArr.value.push(item);
        }
      });
      state.materiallibraryShow = false; //关闭弹窗
    };
    // 打开音乐库
    const MusicLibraryHandle = () => {
      state.musicLibrary.showModal();
      if (currentAudio.value) {
        currentAudio.value.pause();
        currentAudio.value.currentTime = 0;
      }
    };
    // 更新音乐列表
    const updataMusic = (data) => {
      data.forEach((item) => {
        const existingItem = musicListArr.value.find(
          (music) => music.id === item.id
        );
        if (!existingItem) {
          musicListArr.value.push(item);
        }
      });
      // musicListArr.value = musicListArr.value.concat(val);
    };
    // 清空列表
    const emptyMusic = () => {
      musicListArr.value = [];
      if (currentAudio.value) {
        currentAudio.value.pause();
        currentAudio.value.currentTime = 0;
      }
    };
    // 单个删除音乐
    const delectHandle = (item) => {
      console.log(item);
      const index = musicListArr.value?.findIndex((i) => i.id === item.id);
      if (index !== -1) {
        musicListArr.value?.splice(index, 1);
      }
      if (currentAudio.value) {
        currentAudio.value.pause();
        currentAudio.value.currentTime = 0;
      }
    };
    // 切换tab切换
    const changeTab = (info) => {
      state.activeTab = info;
      if (currentAudio.value) {
        currentAudio.value.pause();
        currentAudio.value.currentTime = 0;
      }
    };
    // 提交
    const summitHandle = () => {
      /**
       * @param {type} (0:未选择，1：智能匹配,2:自定义)
       * @param {bgm_list} 音乐列表
       * @param {volume} 音乐列表
       * @param {copyright_range} 版权范围(3-系统音乐随机，1-抖音热门音乐，0-商用版权音乐)
       * @param {musicListArr} 已选中的音乐列表
       * @param {activeTab} 选中的tab（1：智能匹配，2：自定义）
       */
      console.log(state.activeTab, "------", bgm_config.value.type);
      // 不允许用户切换到自定义音乐未选择直接提交
      switch (state.activeTab) {
        case 1:
          bgm_config.value.copyright_range = [3];
          break;
        case 2:
          bgm_config.value.copyright_range = [];
          if (musicListArr.value.length == 0) {
            message.error("请至少添加一首背景音乐");
            return;
          }
          break;
      }
      bgm_config.value.type = state.activeTab;
      bgm_config.value.volume = volume.value / 100;
      bgm_config.value.bgm_list = musicListArr.value;

      // 更新仓库
      store.dispatch("SetVideoMashupItem", {
        key: "bgm_config",
        value: bgm_config.value,
      });
      // 关闭弹窗
      state.visible = false;
      if (currentAudio.value) {
        currentAudio.value.pause();
        currentAudio.value.currentTime = 0;
      }
    };
    const currentAudio = ref(null); //当前音频播放实例
    // 播放音频
    const playAudio = (id) => {
      const audioPlayer = document.getElementById(`audio${id}`);
      // 判断点击播放的是同一个音频
      if (currentAudio.value == audioPlayer) {
        audioPlayer && audioPlayer.play();
      } else {
        // 判断切换了音频
        if (currentAudio.value) {
          currentAudio.value.pause();
          currentAudio.value.currentTime = 0;
        }
        audioPlayer && audioPlayer.play();
      }

      currentAudio.value = audioPlayer;
    };
    // 停止播放音频
    const pauseAudio = (id) => {
      const audioPlayer = document.getElementById(`audio${id}`);
      audioPlayer && audioPlayer.pause();
    };
    // 音频播放结束
    const endPlayAudio = (id) => {
      const audioPlayer = document.getElementById(`audio${id}`);
      if (audioPlayer) {
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
      }
    };
    const toggleCheckbox = () => {
      state.isChecked = !state.isChecked;
    }
    return {
      ...toRefs(state),
      showDrawer,
      onClose,
      materialLibraryHandle,
      MusicLibraryHandle,
      emptyMusic,
      delectHandle,
      summitHandle,
      closeChooseMaterial,
      updataMusic,
      selectList,
      bgm_config,
      volume,
      changeTab,
      musicListArr,
      playAudio,
      pauseAudio,
      endPlayAudio,
      currentAudio,
      toggleCheckbox
    };
  },
});
</script>
<style lang="less" scoped>
.smart-MatchLf,
.smart-MatchRg {
  width: 400px;
  height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 20px;
  border: 1px solid #eaedf1;
  position: relative;
  .smart-Match-title {
    font-weight: 600;
  }
  .smart-Match-desc {
    font-size: 12px;
  }
  .checkbox {
    position: absolute;
    top: -5px;
    right: 0;
  }
}
.smart-MatchLf {
  margin-right: 10px;
}
.volume-adjust {
  justify-content: space-between;
}
.isChecked {
  border: 1px solid #3261fb;
}
.custom-list {
  display: flex;
  flex-wrap: wrap;
  .custom-item,
  .custom-item1 {
    margin-right: 15px;
    margin-top: 15px;
    width: 47%;
    height: 100px;
    border: 1px dashed #eaedf1;
  }
  .custom-item1 {
    background: #f7f7f7;
  }
  .custom-item1-add {
    display: flex;
    font-size: 50px;
    color: #6b7075;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .custom-item1-option {
    height: 100px;
    font-size: 12px;
    padding: 0 10px;
    visibility: hidden;
    color: #6b7075;
    font-weight: 600;
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      width: 27%;
    }
  }
  .custom-item1:hover .custom-item1-option {
    visibility: visible;
  }
  .custom-item1:hover .custom-item1-add {
    display: none;
  }
}
.custom-item {
  display: flex;
  padding: 10px;
  align-items: center;
  position: relative;
}
.custom-item-rg {
  height: 56px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.custom-item-rg-desc {
  display: flex;
  font-size: 14px;
  font-weight: 600;
  justify-content: space-between;
  .material_name {
    width: 150px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.custom-item-rg-video {
  display: flex;
  font-size: 18px;
  align-items: center;
  color: #6b7075;
}
.hover-effect {
  cursor: pointer;
}
.icon-play:hover {
  color: #2878ff !important;
}
.close {
  width: 22px;
  height: 22px;
  text-align: center;
  line-height: inherit;
  position: absolute;
  right: 0;
  font-size: 12px;
  border-radius: 10px;
  border: 1px solid #c1c1c1;
  background: #fff;
  top: -10px;
  visibility: hidden;
  cursor: pointer;
}
.custom-item:hover .close {
  visibility: visible;
}
</style>
